import { type RequiredFields, truthy } from '@gnlab/utils'
import { Form, Button, InputNumber, TimePicker } from 'antd'
import dayjs from 'dayjs'
import { ImportantEditModal } from '@/desktop/components'
import { WordsInput } from '@/desktop/components/words'
import type { Word, ChatFlowTask } from '@/services/features/chat-flows'
import './EditTask.module.less'

interface SaveTask {
  dayTime: SaveDayTime
  words: Word[]
}

interface SaveDayTime {
  day: number
  time: dayjs.Dayjs
}

interface EditingTask {
  dayTime: EditingDayTime
  words: Word[]
}

type EditingDayTime = Partial<SaveDayTime>

export default function EditTaskModal(props: {
  task: false | null | ChatFlowTask // false: 未进行编辑，null: 新增，ChatFlowTask: 修改
  maxDay: number // 当前最大的执行时机天数
  onFinish: (task: ChatFlowTask | null) => void // ChatFlowTask: 保存项目，null: 取消
}) {
  const { task, maxDay, onFinish } = props

  const title = truthy(task) ? '编辑工作流项目' : '添加工作流项目'

  return <ImportantEditModal
    title={title}
    open={task !== false}
    onCancel={() => onFinish(null)}
    width="700px"
    styleName="modal"
  >
    {task !== false ? <Content task={task} maxDay={maxDay} onFinish={onFinish} /> : null}
  </ImportantEditModal>
}

function Content(props: {
  task: null | ChatFlowTask
  maxDay: number
  onFinish: (task: ChatFlowTask | null) => void
}) {
  const { task, maxDay, onFinish } = props

  const initialValues = useMemo<EditingTask>(() => {
    return {
      dayTime: {
        day: task?.day ?? maxDay + 1,
        time: dayjs(task ? { hour: task.hour, minute: task.minute } : { hour: 0, minute: 0 }),
      },
      words: task?.words ?? [],
    }
  }, [task, maxDay])

  const save = useCallback(
    (values: SaveTask) => {
      const {
        dayTime: { day, time },
        words,
      } = values
      onFinish({ day, hour: time.hour(), minute: time.minute(), words })
    },
    [onFinish],
  )

  return <Form initialValues={initialValues} onFinish={save} labelCol={{ span: 3 }}>
    <main>
      <Form.Item
        label="执行时机"
        name="dayTime"
        rules={[
          {
            required: true,
            transform(value: EditingDayTime) {
              return value.day !== undefined && value.time ? 'value' : undefined
            },
            message: '请指定执行时机',
          },
        ]}
        extra="当用户被添加进工作流的当日为第1日，次日为第2日，依此类推。最多不超过30日。"
      >
        <DayTimeInput />
      </Form.Item>

      <Form.Item
        label="发送内容"
        name="words"
        rules={[{ required: true, type: 'array', message: '请指定发送内容' }]}
      >
        <WordsInput enableLibrary />
      </Form.Item>
    </main>
    <footer>
      <Button onClick={() => onFinish(null)}>取消</Button>
      <Button type="primary" htmlType="submit">
        保存
      </Button>
    </footer>
  </Form>
}

function DayTimeInput(props: {
  value?: EditingDayTime
  onChange?: (value: EditingDayTime) => void
}) {
  const { value, onChange } = props as RequiredFields<typeof props, 'value' | 'onChange'>

  const setDay = useCallback(
    (newDay: number | null) => {
      onChange({ ...value, day: newDay ?? 1 })
    },
    [value, onChange],
  )

  const setTime = useCallback(
    (newTime: dayjs.Dayjs | null) => {
      onChange({ ...value, time: newTime ?? undefined })
    },
    [value, onChange],
  )

  return <div styleName="day-time-input">
    <span>
      第<InputNumber min={1} max={30} value={value.day ?? undefined} onChange={setDay} />日
    </span>
    <TimePicker format="HH:mm" value={value.time} onChange={setTime} />
  </div>
}
